﻿// TicTacToe.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>

using namespace std;

bool checkMajorDiagonal(int board[3][3], int state) {
	//主对角线
	for (int i = 0; i < 3; ++i) {
		if (board[i][i] != state) {
			return false;
		}
	}
	return true;
}

bool checkMinorDiagonal(int board[3][3], int state) {
	//次对角线
	for (int i = 0; i < 3; ++i) {
		int j = 2 - i;
		if (board[i][j] != state) {
			return false;
		}
	}
	return true;
}

bool checkHorizontal(int board[3][3], int state, int y) {
	//横
	for (int i = 0; i < 3; ++i) {
		if (board[y][i] != state) {
			return false;
		}
	}
	return true;
}

bool checkVertical(int board[3][3], int state, int x) {
	//竖
	for (int i = 0; i < 3; ++i) {
		if (board[i][x] != state) {
			return false;
		}
	}
	return true;
}

void printBoard(int board[3][3]) {
	for (int i = 0; i < 3; ++i) {
		for (int j = 0; j < 3; ++j) {
			cout << board[i][j] << " ";
		}
		cout << endl;
	}
}


int main()
{
    int board[3][3];
	for (int i = 0; i < 3; ++i)
		for (int j = 0; j < 3; ++j)
			board[i][j] = 0;
    bool win = false;
    //标记是谁在下棋,默认1号先下
    short state = 1;
	while (!win) {
		//获取一个坐标表示下在(x,y)上
		cout << "现在是" << state << "号棋手在下棋(请按\"x y\"的格式下,从(0,0)开始):" << endl;
		int x, y;
		cin >> x >> y;
		if (x < 0 || x > 2 || y < 0 || y > 2) {
			cout << "下棋盘外面了...重来！" << endl;
			continue;
		}

		if (board[y][x] != 0) {
			cout << "这里已经下过了，重来！" << endl;
			continue;
		}

		board[y][x] = state;

		//如果在对角线
		if (!((x == 1 && y != 1) || (y == 1 && x != 1))) {
			if (checkMajorDiagonal(board, state) || checkMinorDiagonal(board, state)) {
				cout << state << "号胜!" << endl;
				break;
			}
		}

		if (checkHorizontal(board, state, y) || checkVertical(board, state, x)) {
			cout << state << "号胜!" << endl;
			break;
		}


		cout << "当前棋盘状态:" << endl;
		printBoard(board);

		if (state == 1)
			state = 2;
		else
			state = 1;
	}

	cout << endl;
	cout << "最终棋盘状态:" << endl;
	printBoard(board);
	return 0;
}